const mongoose = require("mongoose");

const warehouseSchema = new mongoose.Schema(
  {
    warehouseName: {
      type: String,
      required: true,
      unique: true,
    },
    mobile: {
      type: String,
    },
    email: {
      type: String,
    },
    status: {
      type: String,
      enum: ["Active", "Restricted", "Inactive"],
      default: "Active",
    },
    // Optional numeric fields for display if needed:
    Latitude: { type: Number },
    Longitude: { type: Number },
    // GeoJSON location field for geospatial queries:
    location: {
      type: {
        type: String,
        enum: ["Point"],
        default: "Point",
      },
      coordinates: {
        type: [Number], // Format: [longitude, latitude]
        required: function () {
          // Require location if Latitude and Longitude are provided
          return this.Latitude != null && this.Longitude != null;
        },
      },
    },
  },
  { timestamps: true }
);


warehouseSchema.pre("save", function (next) {
  if (
    (!this.location || !this.location.coordinates || this.location.coordinates.length === 0) &&
    this.Latitude != null &&
    this.Longitude != null
  ) {
    this.location = {
      type: "Point",
      coordinates: [this.Longitude, this.Latitude], // Note: Order is [lng, lat]
    };
  }
  next();
});


warehouseSchema.index({ location: "2dsphere" });

module.exports = mongoose.model("Warehouse", warehouseSchema);
